package com.gzxw.mogublog.xo.service.impl;

import com.alibaba.fastjson.JSON;
import com.gzxw.mogublog.commons.config.jwt.Audience;
import com.gzxw.mogublog.commons.config.security.LoginUser;
import com.gzxw.mogublog.utils.JsonUtils;
import com.gzxw.mogublog.utils.StringUtils;
import com.gzxw.mogublog.xo.global.RedisConf;
import com.gzxw.mogublog.xo.global.SysConf;
import com.gzxw.mogublog.xo.service.TokenService;
import io.jsonwebtoken.Claims;
import io.jsonwebtoken.Jwts;
import io.jsonwebtoken.SignatureAlgorithm;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.data.redis.core.StringRedisTemplate;
import org.springframework.stereotype.Service;

import javax.servlet.http.HttpServletRequest;
import java.util.Date;
import java.util.Map;
import java.util.concurrent.TimeUnit;

/**
 * @program: mogublog
 * @author: gzxw
 * @create: 2023-04-26 19:51
 **/
@Service
public class TokenServiceImpl implements TokenService {

    @Value("${audience.base64Secret}")
    private String base64Secret;

    @Value("${tokenHeader}")
    private String tokenHeader;

    @Value("${tokenHead}")
    private String tokenHead;

    @Autowired
    private Audience audience;

    @Autowired
    private StringRedisTemplate stringRedisTemplate;

    // 刷新头肯有效期
    @Override
    public void refreshToken(LoginUser loginUser) {
        // 给用户设置当前在线
        loginUser.setLoginTime(System.currentTimeMillis());

        // 给用户设置过期时间
        loginUser.setExpireTime(loginUser.getLoginTime() + audience.getExpiresSecond());

        // 根据uuid将loginUser缓存
        String key = RedisConf.LOGIN_TOKEN_KEY + ":" + loginUser.getToken();
        stringRedisTemplate.opsForValue().set(key, JSON.toJSONString(loginUser), audience.getExpiresSecond(), TimeUnit.SECONDS);
    }

    // 获取用户信息
    @Override
    public LoginUser getLoginUser(HttpServletRequest request) {

        String header = request.getHeader(tokenHeader);

        if (StringUtils.isNotEmpty(header)) {
            String token = header.substring(tokenHead.length());

            String key = RedisConf.LOGIN_TOKEN_KEY + ":" + token;

            // 从redis中获取
            String loginUserJson = stringRedisTemplate.opsForValue().get(key);

            return JSON.parseObject(loginUserJson, LoginUser.class);
        }
        return null;
    }

    // 删除用户缓存
    @Override
    public void delLoginUser(String token) {

        if (StringUtils.isNotEmpty(token)) {
            String key = RedisConf.LOGIN_TOKEN_KEY + ":" + token;
            stringRedisTemplate.delete(key);
        }

    }
}
